package top.dreamcenter.rss.common.util;

import org.jdom2.Element;
import top.dreamcenter.rss.common.entity.RSS;
import top.dreamcenter.rss.common.entity.RssItem;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class RssHelper extends XMLBuilder{

    /**
     * rss原始对象
     */
    private final RSS rss;

    /**
     * items根节点（channel）
     */
    private Element cycleRoot;

    /**
     * rss 时间格式
     */
    private final SimpleDateFormat sdf = DateTimeUtil.getRssFormat();


    /**
     * RSS 助手
     * @param rss rss原始对象
     */
    public RssHelper(RSS rss) {
        this.rss = rss;
        setChannel();
        addItems();
    }

    /**
     * 构建rss文档
     */
    @Override
    protected void initRoot() {
        root = new Element("rss");
        root.setAttribute("version", "2.0");
    }

    /**
     * 设置channel样式
     */
    private void setChannel() {
        cycleRoot = new Element("channel");
        cycleRoot.addContent(new Element("title").setText(rss.getTitle()));
        cycleRoot.addContent(new Element("link").setText(rss.getLink()));
        cycleRoot.addContent(new Element("description").setText(rss.getDescription()));
        cycleRoot.addContent(new Element("language").setText("zh-cn"));
        cycleRoot.addContent(new Element("lastBuildDate").setText(sdf.format(Calendar.getInstance().getTime())));
        root.addContent(cycleRoot);
    }


    /**
     * 添加item
     */
    private void addItems() {
        for (RssItem rssItem : rss.getItem()) {
            Element item = new Element("item");

            item.addContent(new Element("title").setText(rssItem.getTitle()));
            item.addContent(new Element("description").setText(rssItem.getDescription()));
            item.addContent(new Element("link").setText(rssItem.getLink()));
            item.addContent(new Element("guid").setText(rssItem.getGuid()));
            item.addContent(new Element("pubDate").setText(rssItem.getPubDate()));

            cycleRoot.addContent(item);
        }
    }
}
